package com.tbit.uqbike.webmanager.controller;

import com.tbit.common.entity.vo.MainLogAuditVo;
import com.tbit.uqbike.annos.OperateLog;
import com.tbit.common.constant.MethodEnum;
import com.tbit.common.constant.ModuleEnum;
import com.tbit.uqbike.object.pojo.dto.WorkOrderLogQueryDTO;
import com.tbit.common.entity.pojo.vo.DateResult;
import com.tbit.uqbike.object.pojo.statistics.ExportPowerLog;
import com.tbit.uqbike.object.pojo.statistics.PowerLogDetail;
import com.tbit.uqbike.object.value.LoginInfo;
import com.tbit.uqbike.object.view.JsonResult;
import com.tbit.uqbike.service.business.PowerChangeLogService;
import com.tbit.uqbike.service.business.PowerChangeMonitorConfigService;
import com.tbit.uqbike.webmanager.util.Assert;
import com.tbit.uqbike.webmanager.util.PowerLogExportUtil;
import com.tbit.uqbike.webmanager.util.ServletUtils;
import com.tbit.uqbike.webmanager.util.StringUtil;
import com.tbit.uqbike.webmanager.util.excel.ExportExcelUtil;
import com.tbit.uqbike.webmanager.util.excel.ExportExcelWrapper;
import com.tbit.utils.Excel;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.support.RequestContext;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 换电记录
 *
 * @Author: chen
 * @Description: 统计
 * @Date: 创建于 11:45 2020/3/12
 */
@Validated
@RestController
@Slf4j
@RequestMapping(value = "/powerLogStat", produces = BaseController.MEDIA_JSON_UTF8)
public class PowerChangeLogController extends BaseController {
    @Autowired
    private PowerChangeLogService powerChangeLogService;
    @Autowired
    private PowerChangeMonitorConfigService powerChangeMonitorConfigService;

    @RequestMapping("/statisticsByTime")
    public JsonResult statisticsByTime(Integer accountId, Integer accountUserId, Long startTime, Long endTime, Integer machineType, String isValid) {
        com.tbit.utils.Assert.notNull(accountId, "ver.accountId.notNull");
        com.tbit.utils.Assert.notNull(startTime, "ver.startTime.notNull");
        com.tbit.utils.Assert.notNull(endTime, "ver.endTime.notNull");
        List<Integer> validList = StringUtil.getIntegerList(isValid);
        List<List<DateResult>> list = powerChangeLogService.statisticsByTime(accountId, accountUserId, startTime, endTime, machineType, validList);
        return JsonResult.ok(list);
    }

    @RequestMapping("/queryPage")
    public JsonResult queryPage(WorkOrderLogQueryDTO requestDTO) {
        requestDTO.selfCheck();
        requestDTO.buildPowerRangeSqlCondition(powerChangeMonitorConfigService::getById);
        Integer total = powerChangeLogService.queryCount(requestDTO);
        if (total <= 0) {
            return JsonResult.ok(Collections.emptyList(), total);
        }
        List<PowerLogDetail> list = powerChangeLogService.queryPage(requestDTO);
        return JsonResult.ok(list, total);
    }

    @RequestMapping("/exportByTime")
    public void exportByTime(WorkOrderLogQueryDTO queryDTO, HttpServletResponse response) {
        queryDTO.selfCheck();
        queryDTO.buildPowerRangeSqlCondition(powerChangeMonitorConfigService::getById);
        Assert.notNull(queryDTO.getStartTime(), "ver.startTime.notNull");
        Assert.notNull(queryDTO.getEndTime(), "ver.endTime.notNull");
        RequestContext context = getLogin(ServletUtils.getRequest()).getContext();
        List<PowerLogDetail> list = powerChangeLogService.exportByTime(queryDTO);
        List<String[]> exportList = PowerLogExportUtil.getExportContent(list, null, null, null, context);
        ExportExcelWrapper<String[]> export = new ExportExcelWrapper<>();
        export.exportExcel(context.getMessage("excel_head_powerChange"), context.getMessage("excel_head_powerChange"), null, exportList, response, ExportExcelUtil.EXCEL_FILE_2003);
    }

    @RequestMapping("/exportByTimeAndPersonnel")
    public JsonResult exportByTimeAndPersonnel(Integer accountId, Integer accountUserId,
                                               Long startTime, Long endTime, Integer machineType,
                                               @RequestParam(required = false, value = "regionIds") String regionIds,
                                               @RequestParam(required = false, value = "type") Integer type,
                                               @RequestParam(defaultValue = "10") Integer rowCount,
                                               @RequestParam(defaultValue = "1") Integer pageNO,
                                               HttpServletResponse response) {
        Assert.notNull(accountId, "ver.accountId.notNull");
        Assert.notNull(startTime, "ver.startTime.notNull");
        Assert.notNull(endTime, "ver.endTime.notNull");
        try {
            List<Integer> regionIdList = StringUtil.getIntegerList(regionIds);
            List<ExportPowerLog> list = powerChangeLogService.getByType(accountId, accountUserId, startTime, endTime, 0, 1, regionIdList, type, machineType);
            List<String> cellNameList = new ArrayList<>();
            int row = 1;
            String fileName = "换电记录.xls";
            String title = "换电记录";
            HSSFWorkbook excel = null;
            if (type == 0) {
                cellNameList.add("手机号码");
                cellNameList.add("姓名");
                cellNameList.add("总次数");
                cellNameList.add("有效");
                cellNameList.add("无效");
                cellNameList.add("审核中");
                excel = Excel.createExcel(title, cellNameList);
                for (ExportPowerLog exportPowerLog : list) {
                    List<String> excelData = new ArrayList<>();
                    excelData.add(Optional.ofNullable(exportPowerLog.getPhone()).orElse(""));
                    excelData.add(Optional.ofNullable(exportPowerLog.getName()).orElse(""));
                    excelData.add(exportPowerLog.getTotal().toString());
                    excelData.add(exportPowerLog.getValid() + "");
                    excelData.add(exportPowerLog.getUnValid() + "");
                    excelData.add(exportPowerLog.getUnderReview() + "");
                    excel = Excel.createExcelData(excel, excelData, row);
                    row++;
                }
            } else if (type == 1) {
                cellNameList.add("分区名");
                cellNameList.add("总次数");
                cellNameList.add("有效");
                cellNameList.add("无效");
                cellNameList.add("审核中");
                excel = Excel.createExcel(title, cellNameList);
                for (ExportPowerLog exportPowerLog : list) {
                    List<String> excelData = new ArrayList<>();
                    excelData.add(exportPowerLog.getRegionName());
                    excelData.add(exportPowerLog.getTotal().toString());
                    excelData.add(exportPowerLog.getValid() + "");
                    excelData.add(exportPowerLog.getUnValid() + "");
                    excelData.add(exportPowerLog.getUnderReview() + "");
                    excel = Excel.createExcelData(excel, excelData, row);
                    row++;
                }
            }
            OutputStream out = null;
            String headStr = "attachment; filename=\"" + new String(fileName.getBytes("utf-8"), "ISO8859-1") + "\"";
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", headStr);
            out = response.getOutputStream();
            excel.write(out);
            out.flush();
            out.close();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

        return JsonResult.ok("成功");
    }


    /**
     * 换电总览
     */
    @RequestMapping("/getByType")
    public JsonResult getByType(Integer accountId, Integer accountUserId, Long startTime, Long endTime, Integer machineType,
                                @RequestParam(required = false, value = "regionIds") String regionIds,
                                @RequestParam(required = false, value = "type") Integer type,
                                @RequestParam(defaultValue = "10") Integer rowCount,
                                @RequestParam(defaultValue = "1") Integer pageNO,
                                @RequestParam(required = false, value = "sort") String sort) {
        Assert.notNull(accountId, "ver.accountId.notNull");
        Assert.notNull(startTime, "ver.startTime.notNull");
        Assert.notNull(endTime, "ver.endTime.notNull");
        List<Integer> regionIdList = StringUtil.getIntegerList(regionIds);
        List<ExportPowerLog> list = powerChangeLogService.getByType(accountId, accountUserId, startTime, endTime, rowCount, pageNO, regionIdList, type, machineType);
        if ("asc".equals(sort)) {
            /**升序排列*/
            List<ExportPowerLog> ascendingList = list.stream().sorted(Comparator.comparing(ExportPowerLog::getTotal)).collect(Collectors.toList());
            list = ascendingList;
        } else if ("desc".equals(sort)) {
            /**降序排列*/
            List<ExportPowerLog> descendingList = list.stream().sorted(Comparator.comparing(ExportPowerLog::getTotal).reversed()).collect(Collectors.toList());
            list = descendingList;
        }
        return JsonResult.ok(startPage(list), list.size());

    }

    /**
     * 审核操作
     */
    @RequestMapping("/auditOperation")
    @OperateLog(module = ModuleEnum.POWERCHANGELOG, methods = MethodEnum.POWERCHANGELOG_EDIT)
    public JsonResult auditOperation(@Validated MainLogAuditVo vo, HttpServletRequest request) {
        // 获取用户信息
        LoginInfo loginInfo = getLogin(request);
        powerChangeLogService.updateAudit(vo, loginInfo);
        return JsonResult.ok();
    }

}
